Home:ALL Converter>How to create a `PSObject` in PowerShell

How to create a `PSObject` in PowerShell

Ask Time:2012-06-08T07:19:35         Author:fridojet

Json Formatter

When I heard about the cool properties and methods of PSObjects on MSDN, I thought it would be cool to try them out.

That's what I've done:

Firstly, I created a new instance of the type PSObject.

Then I looked for all those cool members using Get-Member (but they weren't there):

PS .> $plainObj = New-Object PSObject

PS .> $plainObj | Get-Member


   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()

The Problem:

There's no BaseObject property - and no AsPSObject() method. All the cool members aren't there. But why?

Get-Member tells me that my objects is kind (TypeName) of PSCustomObject instead of PSObject. And PSCustomObject doesn't have all these cool members.

But I don't want $plainObj to be a kind of PSCustomObject - I want it to be a kind of PSObject.

My Questions:

  • Why is $plainObj a kind of PSCustomObject although I explicitly used PSObject as -TypeName at $plainObj New-Object PSObject? Any idea?

  • How can I get $plainObj to be a kind of PSObject and not a kind of PSCustomObject?


@RussC Even if I use your script - that's the result:

PS .> $plainObj = New-Object PSObject -property @{ title = 'fridojet' };
$plainObj | Add-Member -MemberType NoteProperty -Name Colour -Value Blue

PS .> $plainobj | Get-Member


   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Colour      NoteProperty System.String Colour=Blue
title       NoteProperty System.String title=fridojet

@RussC Now I managed to create an object which is not kind of PSCustomObject:

PS .> New-Object Object

But even then, I'm not able to create a PSObject (with a BaseObject property and so on):

PS .> [PSObject]::AsPSObject((New-Object Object)) | Get-Member


   TypeName: System.Object

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()

Author:fridojet,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/10941186/how-to-create-a-psobject-in-powershell
yy